﻿using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace BlazorHelper;
/// <summary>
/// 自动依赖注入工具
/// </summary>
public static class AutomaticHelper
{
    /// <summary>
    /// 将serviceType中指定类型的单例服务添加到指定的服务中  
    /// </summary>
    /// <param name="service"></param>
    /// <param name="dllPath">程序集路径</param>
    /// <param name="predicate">注入的程序,请务必加上条件</param>
    /// <exception cref="Exception">未正确加载程序集，请检查路径是否存在程序集</exception>
    /// <returns></returns>
    public static IServiceCollection AddInjectSingleton(this IServiceCollection service, string dllPath, Func<Type, bool> predicate)
    {
        var assembly = Assembly.LoadFrom(dllPath);
        if (assembly == null) throw new Exception("未正确加载程序集，请检查路径是否存在程序集");
        var types = assembly.GetTypes().Where(predicate).ToList();
        foreach (var t in types)
        {
            service.AddSingleton(t);
        }
        return service;
    }
    /// <summary>
    /// 将TService中指定类型的临时服务添加到指定的Microsoft.Extensions.DependencyInjection.IServiceCollection。  
    /// </summary>
    /// <param name="service"></param>
    /// <param name="dllPath">程序集路径</param>
    /// <param name="predicate">注入的程序,请务必加上条件</param>
    /// <exception cref="Exception">未正确加载程序集，请检查路径是否存在程序集</exception>
    /// <returns></returns>
    public static IServiceCollection AddInjectTransient(this IServiceCollection service, string dllPath, Func<Type, bool> predicate)
    {
        var assembly = Assembly.LoadFrom(dllPath);
        if (assembly == null) throw new Exception("未正确加载程序集，请检查路径是否存在程序集");
        var types = assembly.GetTypes().Where(predicate).ToList();
        foreach (var t in types)
        {
            service.AddTransient(t);
        }
        return service;
    }
    /// <summary>
    /// 将serviceType中指定类型的范围服务添加到指定的IServiceCollection中。
    /// </summary>
    /// <param name="service"></param>
    /// <param name="dllPath">程序集路径</param>
    /// <param name="predicate">注入的程序,请务必加上条件</param>
    /// <exception cref="Exception">未正确加载程序集，请检查路径是否存在程序集</exception>
    /// <returns></returns>
    public static IServiceCollection AddInjectScoped(this IServiceCollection service, string dllPath, Func<Type, bool> predicate)
    {
        var assembly = Assembly.LoadFrom(dllPath);
        if (assembly == null) throw new Exception("未正确加载程序集，请检查路径是否存在程序集");
        var types = assembly.GetTypes().Where(predicate).ToList();
        foreach (var t in types)
        {
            service.AddScoped(t);
        }
        return service;
    }
}
